<?php
/**
 * 编辑器上传类
 */
namespace app\proxy\controller;
class Ueditor extends Base
{
    public function _initialize()
    {
        // 调用父类前置方法
        parent::_initialize();

        // 登录校验
        $this->IsLogin();
    }

    /**
     * 运行入口文件
     */
    public function index()
    {
        $params = input(); //接收参数
        $ueditor_config = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("./static/admin/ueditor/php/config.json")), true);
        $action = isset($params['action']) ? $params['action'] : '';
        $path_type = isset($params['path_type']) ? $params['path_type'] : '';
        switch($action){
            case 'config':  
                $result = json_encode($ueditor_config);  
            break;
            /*上传图片*/
            case 'uploadimage':
                if($file = request()->file('upfile'))
                {
                    $info = $file->validate(['size'=>15678000,'ext'=>'jpg,png,gif,jpeg'])->move('./uploads/images/'.$path_type.'/');
                    if(!empty($info))
                    {
                        $url = '/uploads/images/'.$path_type.'/'.str_replace('\\', '/', $info->getSaveName());
                        $ImageSize=GetImageSize('.'.$url);

                        $width=$ImageSize[0];
                        $height=$ImageSize[1];
//                         if($path_type=='techn'){
                        $image = \think\Image::open('.'.$url);
//                            $image->water('./water.png', \think\Image::WATER_NORTHWEST, 30);
                        // 返回图片的宽度
                        $width = $image->width();
                        // 返回图片的高度
                        $height = $image->height();
                        // 返回图片的类型
                        $type = $image->type();
                        // 返回图片的mime类型
                        $mime = $image->mime();
                        // 返回图片的尺寸数组 0 图片宽度 1 图片高度
                        $size = $image->size();
                        $num = strlen($url);
                        $nurl = substr($url,0,$num-4).'1.jpg';

//                            $image->water('./water.png',\think\Image::WATER_NORTHWEST,50)->save('water_image.png'); //加图片水印后保存为 water_image.png
                        $image->tilewater('./water.png',20)->save('.'.$nurl); //图片平铺水印
                        $url = $nurl;

                        $result = json_encode([
                            'url' => $url,
                            'title' => '',
                            'original' => '',
                            'state' => 'SUCCESS'
                        ]);
                    }else
                    {
                        $result = json_encode([
                            'state' => $file->getError()
                        ]);
                    }
                }else
                {
                    $result = json_encode([
                        'state' => '没有上传文件'
                    ]);
                }
            break;
            /* 上传视频 */ 
            case 'uploadvideo':
                if($file = request()->file('upfile'))
                {
                    $info = $file->validate(['size'=>31457280,'ext'=>'mp4'])->move('./uploads/video/'.$path_type.'/');
                    if(!empty($info))
                    {
                        $url = '/uploads/video/'.$path_type.'/'.str_replace('\\', '/', $info->getSaveName());
                        $result = json_encode([
                            'url' => $url,
                            'title' => '',
                            'original' => '',
                            'state' => 'SUCCESS'
                        ]);
                    }else
                    {
                        $result = json_encode([
                            'state' => $file->getError()
                        ]);
                    }
                }else
                {
                    $result = json_encode([
                        'state' => '没有上传文件'
                    ]);
                }
            break;
            /* 上传涂鸦 */  
            case 'uploadscrawl':  
            /* 上传文件 */  
            case 'uploadfile':
                if($file = request()->file('upfile'))
                {
                    $info = $file->validate(['size'=>15678000,'ext'=>'doc,docx,xls,xlsx,ppt,pptx,pdf'])->move('./uploads/file/'.$path_type.'/');
                    if(!empty($info))
                    {
                        $url = '/uploads/file/'.$path_type.'/'.str_replace('\\', '/', $info->getSaveName());
                        $result = json_encode([
                            'url' => $url,
                            'title' => '',
                            'original' => '',
                            'state' => 'SUCCESS'
                        ]);
                    }else
                    {
                        $result = json_encode([
                            'state' => $file->getError()
                        ]);
                    }
                }else
                {
                    $result = json_encode([
                        'state' => '没有上传文件'
                    ]);
                }
            break;
            /* 列出图片 */
            case 'listimage':
                $allowFiles = $ueditor_config['imageManagerAllowFiles'];
                $listSize = $ueditor_config['imageManagerListSize'];
                $path = $ueditor_config['imageManagerListPath'];
                $get = $params;
                $allowFiles = substr(str_replace(".","|",join("",$allowFiles)),1);
                /* 获取参数 */
                $size = isset($get['size']) ? htmlspecialchars($get['size']) : $listSize;
                $start = isset($get['start']) ? htmlspecialchars($get['start']) : 0;
                $end = $start + $size;
                /* 获取文件列表 */
                $path = './uploads/images/'.$path_type.'/';
                $files = $this->getFiles($path,$allowFiles);
                if(!count($files)){
                    $result = json_encode([
                        "state" => "没有图片",
                        "list" => [],
                        "start" => $start,
                        "total" => count($files)
                    ]);
                }else
                {
                    /* 获取指定范围的列表 */
                    $len = count($files);
                    for($i = min($end, $len) - 1, $list = []; $i < $len && $i >= 0 && $i >= $start; $i--){
                        $list[] = $files[$i];
                    }
                    /* 返回数据 */
                    $result = json_encode([
                        "state" => "SUCCESS",
                        "list" => $list,
                        "start" => $start,
                        "total" => count($files)
                    ]);
                }
            break;
            /**
             * 列出视频
             */
            case 'listvideo':
                $allowFiles = $ueditor_config['videoManagerAllowFiles'];
                $listSize = $ueditor_config['videoManagerListSize'];
                $path = $ueditor_config['videoManagerListPath'];
                $get = $params;
                $allowFiles = substr(str_replace(".","|",join("",$allowFiles)),1);
                /* 获取参数 */
                $size = isset($get['size']) ? htmlspecialchars($get['size']) : $listSize;
                $start = isset($get['start']) ? htmlspecialchars($get['start']) : 0;
                $end = $start + $size;
                /* 获取文件列表 */
                $path = './uploads/video/'.$path_type.'/';
                $files = $this->getFiles($path,$allowFiles);
                if(!count($files)){
                    $result = json_encode([
                        "state" => "没有视频",
                        "list" => [],
                        "start" => $start,
                        "total" => count($files)
                    ]);
                }else
                {
                    /* 获取指定范围的列表 */
                    $len = count($files);
                    for($i = min($end, $len) - 1, $list = []; $i < $len && $i >= 0 && $i >= $start; $i--){
                        $list[] = $files[$i];
                    }
                    /* 返回数据 */
                    $result = json_encode([
                        "state" => "SUCCESS",
                        "list" => $list,
                        "start" => $start,
                        "total" => count($files)
                    ]);
                }
            break;
            /**
             * 列出附件
             */
            case 'listfile':
                $allowFiles = $ueditor_config['fileManagerAllowFiles'];
                $listSize = $ueditor_config['fileManagerListSize'];
                $path = $ueditor_config['fileManagerListPath'];
                $get = $params;
                $allowFiles = substr(str_replace(".","|",join("",$allowFiles)),1);
                /* 获取参数 */
                $size = isset($get['size']) ? htmlspecialchars($get['size']) : $listSize;
                $start = isset($get['start']) ? htmlspecialchars($get['start']) : 0;
                $end = $start + $size;
                /* 获取文件列表 */
                $path = './uploads/file/'.$path_type.'/';
                $files = $this->getFiles($path,$allowFiles);
                if(!count($files)){
                    $result = json_encode([
                        "state" => "没有附件",
                        "list" => [],
                        "start" => $start,
                        "total" => count($files)
                    ]);
                }else
                {
                    /* 获取指定范围的列表 */
                    $len = count($files);
                    for($i = min($end, $len) - 1, $list = []; $i < $len && $i >= 0 && $i >= $start; $i--){
                        $list[] = $files[$i];
                    }
                    /* 返回数据 */
                    $result = json_encode([
                        "state" => "SUCCESS",
                        "list" => $list,
                        "start" => $start,
                        "total" => count($files)
                    ]);
                }
            break;
            default:  
                $result = json_encode([  
                    'state' => '请求地址出错'  
                ]);  
            break;
        }
        /* 输出结果 */  
        if (isset($params["callback"])) {  
            if (preg_match("/^[\w_]+$/", $params["callback"])) {  
                echo htmlspecialchars($params["callback"]) . '(' . $result . ')';  
            } else {  
                echo json_encode([  
                    'state' => 'callback参数不合法'  
                ]);  
            }  
        } else {  
            echo $result;  
        }
    }

    /*
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param array $files
     * @return array
    */
    private function getFiles($path,$allowFiles,&$files = [])
    {
        if(!is_dir($path)) return null;
        if(substr($path,strlen($path)-1) != '/') $path .= '/';
        $handle = opendir($path);
        while(false !== ($file = readdir($handle))){
            if($file != '.' && $file != '..'){
                $path2 = $path.$file;
                if(is_dir($path2)){
                    $this->getFiles($path2,$allowFiles,$files);
                }else{
                    if(preg_match("/\.(".$allowFiles.")$/i",$file)){
                        $files[] = [
                            'url' => substr($path2,1),
                            'mtime' => filemtime($path2)
                        ];
                    }
                }
            }
        }       
        return $files;
    }
}